package indicators

import (
	"strings"
	"sync"

	"gitee.com/lyuanbo/stock-trade/internal/pkg/mq"
	"gitee.com/lyuanbo/stock-trade/internal/pkg/stock/constant"
	"github.com/maypok86/otter"
)

type Indicator interface {
	Name() string
	Run()
	ListenRealtime()
	ListenKline()
}

// 指标注册表
var indicatorMap = make(map[string]Indicator)

// 正在运行的指标列表
var indicators []string
var mux sync.Mutex
var store otter.Cache[string, []*constant.Kline]

func Register(name string, idc Indicator) {
	mux.Lock()
	defer mux.Unlock()

	if _, ok := indicatorMap[name]; ok {
		panic("indicator already registered: " + name)
	}

	indicatorMap[name] = idc
}

func init() {
	// 添加指标订阅
	_ = mq.Default().Subscribe(constant.MqTopicTypeIndicatorAdd, "", func(arr []string) {
		// 判断是否存在该指标
		mux.Lock()
		for _, indicator := range indicators {
			if strings.Contains(indicator, arr[0]) {
				continue
			}

			arr = append(arr, indicator)
		}
		mux.Unlock()
	})

	// 移除指标订阅
	_ = mq.Default().Subscribe(constant.MqTopicTypeIndicatorRemove, "", func(arr []string) {
		mux.Lock()
		for i, indicator := range indicators {
			if strings.Contains(indicator, arr[0]) {
				// 移除该指标
				indicators = append(indicators[:i], indicators[i+1:]...)
				i--
			}
		}
		mux.Unlock()
	})
}

func Run(cache otter.Cache[string, []*constant.Kline], arr ...string) {
	store = cache

	if len(arr) > 0 {
		indicators = arr
	}

	for _, indicator := range indicators {
		if idc, ok := indicatorMap[indicator]; ok {
			go func() {
				idc.Run()
				idc.ListenRealtime()
				idc.ListenKline()
			}()
		}
	}
}
